import Vue from "vue"
let prototype = Vue.prototype;

function findApi(name) {
    let pos = name.indexOf('.');
    if (pos > 0) {
        let temp, arr = name.split('.');
        for (let i = 0; i < arr.length; i++) {
            if (i == 0) {
                temp = prototype.$apis[arr[i]] || {};
            } else {
                temp = temp[arr[i]] || {};
            }
        }
        return temp;
    }

    return name;
}

let upload = async (args) => {
    const rule = findApi(args.api || '');
    if (JSON.stringify(rule) === "{}") {
        throw "找不到API：" + args.api;
    }

    (rule.showLoading) && prototype.$loading.show('上传中');

    let [error, response] = await uni.uploadFile({
        url: prototype.$config.root + rule.url,
        filePath: args.path,
        name: args.name || 'file',
        formData: args.data || {},
    });

    (rule.showLoading) && prototype.$loading.hide();

    if (error || response.statusCode != 200) {
        prototype.$utils.toast('网络错误');
        throw "网络错误";
    }

    return Promise.resolve(JSON.parse(response.data));
}

export default upload
